/*
 * Copyright (c) 2019. Mikes. All rights reserved.
 *
 * You can contact me with sending email to bWlrZXNfMjAxMkAxNjMuY29t for more information!
 */

package com.climber.android.ui

import android.content.Intent
import android.os.Bundle
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.PagerAdapter
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.climber.android.R
import com.climber.android.commonres.app.AppAccount
import com.climber.android.commonres.ui.BaseMVPActivity
import com.climber.android.commonres.ui.BlankFragment
import com.climber.android.commonsdk.app.AppConstants
import com.climber.android.commonsdk.app.AppFormStorage
import com.climber.android.commonsdk.arouter.ARouterPathConstants
import com.climber.android.commonsdk.event.BusProvider
import com.climber.android.commonsdk.event.CommonBusEvent
import com.climber.android.commonsdk.util.SnackbarUtils
import com.climber.android.util.ExitUtil
import io.ganguo.library.mvp.arouter.ARouterUtils
import io.ganguo.library.mvp.fragment_handle.FragmentHandleBackUtil
import io.ganguo.library.mvp.ui.mvp.IPresenter
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.ganguo.library.mvp.util.MainLooper
import io.ganguo.library.mvp.util.StatusBarUtils
import io.ganguo.library.mvp.util.UIUtils
import io.library.android.net.NetworkManager
import io.library.android.net.NetworkUtils
import io.library.android.net.annoation.NetStateListen
import io.library.android.net.annoation.NetStateSubscribe
import io.library.android.net.type.NetType
import kotlinx.android.synthetic.main.app_activity_material_main.*
import org.greenrobot.eventbus.Subscribe

enum class TabKey(val tab : String) {
    MALL("tab"),
    SOCIAL("social"),
    PUBLISH("publish"),
    MESSAGE("message"),
    USER_CENTER("user");

    companion object{
        fun defaultTab() = SOCIAL
    }
}

@Route(path = ARouterPathConstants.PATH_APP_HOME)
@NetStateListen
class MaterialMainActivity : BaseMVPActivity<IPresenter>() {
    inner class MaterialTabPagerAdapter(
        private val fragmentsList: MutableList<Fragment>,
        fm: FragmentManager
    ) :
        FragmentPagerAdapter(fm) {
        private var currentFragment: Fragment? = null

        fun getCurrentFragment(): Fragment? = currentFragment

        override fun getItemPosition(`object`: Any): Int {
            return PagerAdapter.POSITION_NONE
        }

        override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
            super.setPrimaryItem(container, position, `object`)
            currentFragment = `object` as Fragment
        }

        override fun getItem(index: Int): Fragment = fragmentsList[index]

        override fun getCount(): Int {
            return fragmentsList.size
        }
    }

    private var mSelectTabIndex = TabKey.defaultTab().ordinal

    override fun setupActivityComponent(appComponent: AppComponent) {
    }

    override fun changeStatusColor(): Boolean = false

    override fun getLayoutResourceId(): Int = R.layout.app_activity_material_main

    override fun initView() {
        window.setFlags(
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN
        )
        StatusBarUtils.setStatusBarDarkFont(this, true)

        val fragmentsList = mutableListOf<Fragment>()
        // mall
        val mallFragment = ARouter.getInstance().build(ARouterPathConstants.PATH_FRAGMENT_MALL).navigation() as? Fragment
        if(mallFragment != null) {
            fragmentsList.add(mallFragment)
        } else{
            fragmentsList.add(BlankFragment())
        }
        // social
        val socialFragment = ARouter.getInstance().build(ARouterPathConstants.PATH_FRAGMENT_SOCIAL).navigation() as? Fragment
        if(socialFragment != null) {
            fragmentsList.add(socialFragment)
        } else{
            fragmentsList.add(BlankFragment())
        }
        // publish
        fragmentsList.add(BlankFragment())
        // message
        val messageFragment = ARouter.getInstance().build(ARouterPathConstants.PATH_FRAGMENT_MESSAGE).navigation() as? Fragment
        if(messageFragment != null) {
            fragmentsList.add(messageFragment)
        } else{
            fragmentsList.add(BlankFragment())
        }
        // UserCenter
        val userCenterFragment = ARouter.getInstance().build(ARouterPathConstants.PATH_FRAGMENT_USER_CENTER).navigation() as? Fragment
        if(userCenterFragment != null) {
            fragmentsList.add(userCenterFragment)
        } else{
            fragmentsList.add(BlankFragment())
        }

        val viewPagerAdapter = MaterialTabPagerAdapter(fragmentsList, supportFragmentManager)

        viewPager.adapter = viewPagerAdapter
        viewPager.offscreenPageLimit = viewPagerAdapter.count - 1
        viewPager.setScroll(false)
        viewPager.currentItem = mSelectTabIndex

        bottomBar.setBadgeBackgroundColor(UIUtils.getColor(R.color.common_warning_red))

        if(AppFormStorage.isFirstLaunchAfterUpgrade(true)){

        }
    }

    override fun initListener() {
        bottomBar.setOnTabSelectListener { tabId ->
            changeUIWhenSelectTab(tabId)
        }

        bottomBar.setOnTabReselectListener { tabId ->
            changeUIWhenSelectTab(tabId)
        }

        bottomBar.setTabSelectionInterceptor { _, newTabId ->
            if (!AppAccount.isAuthenticated()) {
                if(newTabId == R.id.tab_fragment_3
                        || newTabId == R.id.tab_fragment_4
                        || newTabId == R.id.tab_fragment_5){
                    ARouterUtils.navigationWithDefaultAnim(ARouterPathConstants.PATH_SIGN_IN, ARouterPathConstants.INVALID_FLAG, null)

                    return@setTabSelectionInterceptor true
                }
                return@setTabSelectionInterceptor false
            } else if(newTabId == R.id.tab_fragment_3){
                ARouter.getInstance().build(ARouterPathConstants.PATH_SIGN_IN)
                        .withTransition(R.anim.cbase__alpha_in_activity, R.anim.cbase__alpha_out_activity)
                        .navigation()
                return@setTabSelectionInterceptor true
            } else{
                return@setTabSelectionInterceptor false
            }
        }
    }

    override fun initData() {
    }

    private fun changeUIWhenSelectTab(tabId: Int) {
        when (tabId) {
            R.id.tab_fragment_1 -> {
                mSelectTabIndex = TabKey.MALL.ordinal
            }
            R.id.tab_fragment_2 -> {
                mSelectTabIndex = TabKey.SOCIAL.ordinal
            }
            R.id.tab_fragment_3 -> {
                mSelectTabIndex = TabKey.PUBLISH.ordinal
            }
            R.id.tab_fragment_4 -> {
                mSelectTabIndex = TabKey.MESSAGE.ordinal
            }
            R.id.tab_fragment_5 -> {
                mSelectTabIndex = TabKey.USER_CENTER.ordinal
            }
            else -> {
                mSelectTabIndex = TabKey.defaultTab().ordinal
            }
        }

        viewPager.setCurrentItem(mSelectTabIndex, false)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)

        preChooseTab(intent.extras)
    }

    override fun onBackPressed() {
        if (!FragmentHandleBackUtil.handleBackPress(this)) {
            NetworkManager.getDefault().unregisterAllObservers()
            ExitUtil.exitGoLauncher(this)
        }
    }

    private fun preChooseTab(bundle: Bundle?) {
        if(bundle == null) return

        when (bundle.getString(AppConstants.PARAM_TAB)) {
            TabKey.MALL.tab -> {
                bottomBar.selectTabWithId(R.id.tab_fragment_1)
                val childTabName = bundle.getString(AppConstants.PARAM_TAB_CHILD)
                if(childTabName != null){
                    MainLooper.getInstance().postDelayed({
                        BusProvider.getInstance().post(CommonBusEvent.ChooseMallChildTabEvent(childTabName))
                    }, 200)
                }
            }
            TabKey.SOCIAL.tab -> {
                bottomBar.selectTabWithId(R.id.tab_fragment_2)
                val childTabName = bundle.getString(AppConstants.PARAM_TAB_CHILD)
                if(childTabName != null){
                    MainLooper.getInstance().postDelayed({
                        BusProvider.getInstance().post(CommonBusEvent.ChooseSocialChildTabEvent(childTabName))
                    }, 200)
                }
            }
            TabKey.MESSAGE.tab -> {
                bottomBar.selectTabWithId(R.id.tab_fragment_3)
                val childTabName = bundle.getString(AppConstants.PARAM_TAB_CHILD)
                if(childTabName != null){
                    MainLooper.getInstance().postDelayed({
                        BusProvider.getInstance().post(CommonBusEvent.ChooseMessageChildTabEvent(childTabName))
                    }, 200)
                }
            }
            TabKey.USER_CENTER.tab -> {
                bottomBar.selectTabWithId(R.id.tab_fragment_5)
            }
            else -> {
                bottomBar.selectTabWithId(R.id.tab_fragment_3)
            }
        }
    }

    @Subscribe
    fun receiveTokenChangeEvent(event : CommonBusEvent.TokenChangeEvent){
        if(!event.authorizated){
            // 退出登录, 默认选择 社区 Tab
            bottomBar.selectTabWithId(R.id.tab_fragment_2)
        }
    }

    @Subscribe
    fun onReceiveUnreadMsgCountEvent(event : CommonBusEvent.UnreadMsgCountEvent){
        val badgeCount = event.unreadCount
        bottomBar.getTabWithId(R.id.tab_fragment_4).setBadgeCount(badgeCount)
    }

    @NetStateSubscribe
    fun onNetworkStateChange(netType: NetType) {
        if (netType == NetType.NONE) {
            SnackbarUtils.with(viewPager)
                .setMessage(getString(R.string.app_network_error))
                .setMessageColor(UIUtils.getColor(R.color.common_white_full))
                .setBgColor(UIUtils.getColor(R.color.common_warning_red))
                .setDuration(SnackbarUtils.LENGTH_INDEFINITE)
                .setAction("前往", UIUtils.getColor(R.color.common_blue)) {
                    NetworkUtils.openWirelessSettings()
                }
                .show()
        } else {
            SnackbarUtils.dismiss()
        }
    }
}
